"""
    Controller for viewing and editing user's filters.
"""

from turbogears.controllers import Controller
from turbogears import expose, redirect, identity
from mnemoply.model import UserFilter

class UserSettingsController(Controller):
    def __init__(self):
        Controller.__init__(self)

    @expose("genshi:mnemoply.templates.user_settings")
    def index(self):
        userfilters = list(UserFilter.selectBy(user=identity.current.user).orderBy('ordinal'))
        userfilters.sort(key=lambda x: x.controller)

        return dict(
            title=_("Manage your settings"),
            filters=userfilters
            )

    @expose("genshi:mnemoply.templates.user_settings")
    def del_filter(self, fid):
        fid = int(fid)
        cur_filter = UserFilter.get(fid)

        ordinal = cur_filter.ordinal
        cur_filter.destroySelf()

        for cur_filter in UserFilter.selectBy(user=identity.current.user, controller=cur_filter.controller):
            if cur_filter.ordinal > ordinal:
                cur_filter.ordinal -= 1

        raise redirect("./")

    @expose("genshi:mnemoply.templates.user_settings")
    def up_filter(self, fid):
        cur_filter = UserFilter.get(int(fid))
        if cur_filter.ordinal > 1:
            prev = list(UserFilter.selectBy(user=identity.current.user,
                    controller=cur_filter.controller, ordinal=cur_filter.ordinal - 1))
            if len(prev):
                prev_filter = prev[0]
                (cur_filter.ordinal, prev_filter.ordinal) = (prev_filter.ordinal, cur_filter.ordinal)

        raise redirect("./")

    @expose("genshi:mnemoply.templates.user_settings")
    def down_filter(self, fid):
        cur_filter = UserFilter.get(int(fid))
        max_ordinal = UserFilter.selectBy(user=identity.current.user, controller=cur_filter.controller).max('ordinal')
        if cur_filter.ordinal < max_ordinal:
            next = list(UserFilter.selectBy(user=identity.current.user, controller=cur_filter.controller,
                    ordinal=cur_filter.ordinal + 1))
            if len(next):
                next_filter = next[0]
                (cur_filter.ordinal, next_filter.ordinal) = (next_filter.ordinal, cur_filter.ordinal)

        raise redirect("./")

exposed = UserSettingsController()
